<?php

namespace App\Http\Controllers\Admin;

use App\Exports\AllExport;
use App\Http\Requests\Admin\BaseRequest;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Admin\Traits\AdminTrait;
use App\Models\Admin\AdminUser;
use DB;
use Illuminate\Support\Facades\Auth;
use Maatwebsite\Excel\Facades\Excel;

class AdminController extends Controller
{
    use AdminTrait;
    public $user_id;
    public $jwt_user_info;

    public function __construct()
    {
        if (is_object(auth('admin')->user())) {
            $this->jwt_user_info = auth('admin')->user();
            $this->user_id = $this->jwt_user_info->id;
        } else {
            if (!$this->user_id) {
                // dd(auth('admin')->manager()->getPayloadFactory()->buildClaimsCollection()->toPlainArray());
                $this->user_id = auth('admin')->manager()->getPayloadFactory()->buildClaimsCollection()->toPlainArray()['sub'];
                $user_info = AdminUser::find($this->user_id);
                $this->jwt_user_info = $user_info;
            }
        }

        // 本地判断是否开启mysql查询日志
        if (env('APP_ENV', 'pro') == 'local' && env('DB_LOG', false)) {
            \Illuminate\Support\Facades\DB::connection()->enableQueryLog();
        }
    }

    //自定义提示信息
    public $vali_msg = [
        'required' => ':attribute不存在',
        'integer' => ':attribute不是整型',
        'min' => ':attribute最小值为:min',
        'max' => ':attribute最大值为:max',
        'in' => '::attribute 必须为以下值: :values',
        'filled' => '::attribute 不能传空值',
        'numeric' => '::attribute 必须是数字',
        'array' => '::attribute 必须是数组',
        'date' => '::attribute 必须是日期格式',
        'digits_between' => '::attribute长度必须在:min到:max之间',
        'old_pwd.digits_between' => '原密码长度必须在:min到:max之间',
        'new_pwd.digits_between' => '新密码长度必须在:min到:max之间',
        'new_pwd.different' => '新密码必须和旧密码不同',
        'new_pwd.required' => '新密码不能为空',
        'old_pwd.required' => '旧密码不能为空',
        'image' => '必须上传图片',
        'new_pwd.regex' => '密码必须为字母、数字或以下符号-.',
        'string' => '::attribute必须为字符型',
        'exists' => '::attribute找不到',
        'email' => '邮箱格式不对',
        'mobile.digits' => '手机号格式不对',
    ];

    //自定义验证规则
    public $vali_rules = [
        'page' => 'bail|required|integer|min:1',
        'size' => 'required|integer|min:1',
    ];

    //页码
    public $page = '';

    //条数
    public $size = '';

    //获取起始位置
    public $skip = '';

    //获取页码以及条数
    public function getPageAndSize($data)
    {
        $this->page = !empty($data['page']) ? $data['page'] : 1;
        $this->size = !empty($data['size']) ? $data['size'] : 10;
        $this->skip = ($this->page - 1) * $this->size;
    }

    public function index(BaseRequest $request)
    {
        $data = ['list' => $this->_list($request)] + $request->all();
        if (method_exists($this, 'beforeIndex')) {
            $data = $data + $this->beforeIndex();
        }
        //return $data;
        return response()->json(['errcode' => 0, 'data' => $data, 'errmsg' => 'ok']);
    }

    /*public function info(Request $request)
    {

    }*/

    public function add(BaseRequest $request)
    {
        isset($this->unique_id) && $this->unique_id = 0;

        if (true !== $msg = $this->validate_form($request)) {
            //验证未通过
            return response()->json(['errcode' => '40012', 'errmsg' => $msg]);
        }

        //去除数组
        $data = $this->setRequestField($request->all());

        if (method_exists($this, 'otherData')) {
            $data = $this->otherData($data, $request->all());
        }

        DB::beginTransaction();
        try {
            //执行添加操作
            $result = $this->model->create($data);
            //后置操作
            if (method_exists($this, 'afterData')) {
                $this->afterData($result, $request->all());
            }

            if (method_exists($this->model, 'addLog')) {
                $this->model->addLog($result, [], 1);
            }
            //Log::info($result);
            DB::commit();
            return response()->json(['errcode' => 0, 'errmsg' => 'ok']);
        } catch (\Exception $e) {
            report($e);
            DB::rollBack();
            return $e->getMessage();
            return response()->json(['errcode' => 40006, 'errmsg' => '添加失败']);
        }
    }

    public function edit(BaseRequest $request)
    {
        isset($this->unique_id) && $this->unique_id = $request->id;

        if (true !== $msg = $this->validate_form($request)) {
            //验证未通过
            return response()->json(['errcode' => '40012', 'errmsg' => $msg]);
        }

        //获取模型
        $info = $this->model->findOrFail($request->id);

        DB::beginTransaction();
        try {
            //赋值
            foreach ($this->setRequestField($request->all(), true) as $k => $v) {
                if (!is_array($v)) {
                    $info->$k = $v;
                }
            }
            $perInfo = $info->getOriginal(); //获取修改之前的字段
            //执行修改操作
            $info->save();
            $nextInfo = $info->getChanges(); //获取修改之后的字段
            //后置操作
            if (method_exists($this, 'afterData')) {
                $this->afterData($info, $request->all());
            }


            if (method_exists($this->model, 'addLog')) {
                if (!empty($nextInfo)) {
                    $this->model->addLog($perInfo, $nextInfo, 2);
                }
            }

            DB::commit();
            return response()->json(['errcode' => 0, 'errmsg' => 'ok']);
        } catch (\Exception $e) {
            report($e);
            DB::rollBack();
            //            return $e->getMessage();
            return response()->json(['errcode' => 40007, 'errmsg' => '修改失败']);
        }
    }

    public function delete(BaseRequest $request)
    {
        //检查是否能删除
        if (method_exists($this, 'checkDelete')) {
            if (true !== $msg = $this->checkDelete($request->id)) {
                return response()->json($msg);
            }
        }
        //执行删除
        $info = $this->model->findOrFail($request->id);

        if (method_exists($this->model, 'addLog')) {
            $this->model->addLog($info->toArray(), [], 3, __FUNCTION__);
        }

        if ($info->delete()) {
            return response()->json(['errcode' => 0, 'errmsg' => 'ok']);
        } else {
            return response()->json(['errcode' => 40011, 'errmsg' => '删除失败']);
        }
    }

    public function changeStatus(BaseRequest $request)
    {
        $id = $request->query('id', 0);
        $status = $request->query('status', 0);
        if (!is_numeric($id)) return $this->error(['40016', '参数错误']);
        $info = $this->model->find($id);
        if (empty($info)) return $this->error(['40009', '信息不存在']);
        if (method_exists($this->model, 'addLog')) {
            $this->model->addLog($info->toArray(), ['status' => $status], 2);
        }
        $info->status = $status;
        if ($info->save()) {
            return $this->success();
        } else {
            return $this->error(['40007', '修改失败']);
        }
    }

    protected function _export($arr, $head, $name, $MergeCells = [], $width = [], $setBold = [], $color = [])
    {
        try {
            $excel = new AllExport($arr, $head, $name);
            $abc = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'S', 'Y', 'Z'];
            $abcs = [];
            $ar_num = 0;
            foreach ($abc as $val) {
                $ar_num++;
                $abcs[$val] = 15;
            }
            if (!$width) $width = $abcs;
            $excel->setColumnWidth($width); //设置列宽 "A" => 30, "B" => 30
            $excel->setRowHeight([1 => 50]); //设置行高，$i为数据行数  1 => 50
            $excel->setFont(['A1:Z1' => '宋体']); //设置 字体
            $excel->setFontSize(['A1:Z1265' => 14]); //设置 字体大小
            if (!$setBold) $setBold = ['A1:Z1' => true];
            $excel->setBold($setBold); //设置区域单元格字体粗体 ['A1:Z1' => true]
            $excel->setMergeCells($MergeCells); //合并单元格
            $excel->setColor($color);
            //            $excel->setBorders(['A2:D5' => '#000000']);//设置边框颜色
            //日志
            /*$OrderList = new OrderList;
            $Export = new ExportsController($OrderList);
            $Export->addLog([], [], 7, $model, $method, 3, $pid);*/
            return Excel::download($excel, '导出文件.xlsx');
        } catch (\Exception $e) {
            return [
                'code' => 500,
                'data' => [
                    'err' => 'export_failed',
                    'err_msg' => $e->getMessage()
                ],
                'msg' => '导出失败'
            ];
        }
    }
}
